package logic

import (
	"fmt"
	"log"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/models/message"
	"yundian/internel/pkg/authorized"
	"yundian/internel/pkg/utils"
)

const (
	TemplateIdFinish   = "v1bbpgpti372bs9jIzT9KMN_66ZGjf9WvCTtpK4ObwA" // 归还通知模板
	TemplateIdOrder    = "NaMpuMhn9BAHZHtBOjPhGoQnfSjsWFVrfmm5IvSEOOE" // 订单状态通知模板
	TemplateIdEvaluate = "a3Iv2WMm497jJETnzpSvET3gwAomvj01xHRhSDoW3S8" // 服务评价提醒
)

var taskMessageIds []int

// WeChatAppletMessageFixedPush 微信小程序订阅消息推送-固定提醒
func (task *TaskLogic) WeChatAppletMessageFixedPush(typeNum uint8) {
	var err error
	var messageRes authorized.MessageSubscribePostResp
	var accessToken authorized.ResAccessToken

	wxConfig := NewSettingLogic().GetPaySetting()
	if accessToken, err = authorized.GetAppAccessToken(wxConfig.AppId, wxConfig.AppSecret); err != nil {
		log.Println("WeChatAppletMessagePush-ERROR", err, accessToken)
		return
	}

	h, _ := time.ParseDuration("-10h")
	minTime := time.Now().Add(h).Format("2006-01-02 15:04:05")
	messageList := dao.NewMessageDao().GetWaitFixedRemindRss(typeNum, minTime).Unwrap().([]*message.MessageFixedModel)
	params := map[string]interface{}{}
	for _, item := range messageList {
		if TemplateIdEvaluate == item.TemplateId {
			params = task.WeChatAppEvaluateTemplate(item)
		} else {
			dao.NewMessageDao().UpdateIdFixedRemindRss(item.Id, uint8(helper.TypeNumMessageStatusCancel))
			log.Println("WeChatAppletMessageFixedPush->TemplateId-err", item.TemplateId, params)
			continue
		}

		// {"errcode":0,"errmsg":"ok","msgid":1967769668186603521}
		// {"errcode":43101,"errmsg":"user refuse to accept the msg rid: 60fa3f8e-1f00a7b0-2f34f8d7"}
		if messageRes, err = authorized.MessageSubscribePost(accessToken.AccessToken, params); err != nil {
			log.Println("MessageSubscribePost-err", err)
		}
		status := helper.TypeNumMessageStatusFail
		if messageRes.Errcode == 0 {
			status = helper.TypeNumMessageStatusSuccess
		}
		if messageRes.Errcode == 43101 {
			status = helper.TypeNumMessageStatusCancel
		}

		log.Println("MessageSubscribePost-res", messageRes, params)
		dao.NewMessageDao().UpdateIdFixedRemindRss(item.Id, uint8(status))
	}
}

// 微信小程序订阅消息推送
func (task *TaskLogic) WeChatAppletMessagePush() {
	if len(taskMessageIds) > 0 {
		log.Println("WeChatAppletMessagePush-await", taskMessageIds)
		return
	}

	var err error
	var messageRes authorized.MessageSubscribePostResp
	var accessToken authorized.ResAccessToken

	wxConfig := NewSettingLogic().GetPaySetting()
	if accessToken, err = authorized.GetAppAccessToken(wxConfig.AppId, wxConfig.AppSecret); err != nil {
		log.Println("WeChatAppletMessagePush-ERROR", err, accessToken)
		return
	}

	messageList := dao.NewMessageDao().GetWaitOrderRemindRss(TemplateIdFinish, TemplateIdOrder).Unwrap().([]*message.OrderAndMessageModel)
	params := map[string]interface{}{}
	for _, item := range messageList {
		taskMessageIds = append(taskMessageIds, item.Id)
		if TemplateIdFinish == item.TemplateId && item.State == helper.TypeNumOrderStatusFinish {
			params = task.WeChatAppChargeTemplate(item)
		} else if TemplateIdOrder == item.TemplateId && item.State == helper.TypeNumOrderStatusService {
			params = task.WeChatAppOrderStatusTemplate(item)
		} else {
			dao.NewMessageDao().UpdateIdOrderRemindRss(item.Id, uint8(helper.TypeNumMessageStatusCancel))
			log.Println("TemplateId-err", item.TemplateId, params)
			taskMessageIds = taskMessageIds[:len(taskMessageIds)-1]
			continue
		}

		// {"errcode":0,"errmsg":"ok","msgid":1967769668186603521}
		// {"errcode":43101,"errmsg":"user refuse to accept the msg rid: 60fa3f8e-1f00a7b0-2f34f8d7"}
		if messageRes, err = authorized.MessageSubscribePost(accessToken.AccessToken, params); err != nil {
			log.Println("MessageSubscribePost-err", err)
		}
		status := helper.TypeNumMessageStatusFail
		if messageRes.Errcode == 0 {
			status = helper.TypeNumMessageStatusSuccess
		}
		if messageRes.Errcode == 43101 {
			status = helper.TypeNumMessageStatusCancel
		}

		log.Println("MessageSubscribePost-res", messageRes, params)
		dao.NewMessageDao().UpdateIdOrderRemindRss(item.Id, uint8(status))
		taskMessageIds = taskMessageIds[:len(taskMessageIds)-1]
	}
}

// 订单号{{character_string1.DATA}}
// 商品信息{{thing2.DATA}}
// 租借时长{{thing4.DATA}}
// 产生费用{{amount5.DATA}}
// 租借地点{{thing3.DATA}}
// 归还通知
func (task *TaskLogic) WeChatAppChargeTemplate(item *message.OrderAndMessageModel) map[string]interface{} {
	h, m, _ := utils.SecondFormat(int(item.EndAt - item.CreateAt))
	timeLen := fmt.Sprintf("%s小时%s分", utils.AddZero(h), utils.AddZero(m))
	amountStr := fmt.Sprintf("￥%.2f", float32(item.SettlementMoney)/100)

	data := map[string]interface{}{
		"character_string1": map[string]interface{}{"value": item.TradeNo},
		"thing2":            map[string]interface{}{"value": "中曼速充共享充电器"},
		"thing4":            map[string]interface{}{"value": timeLen},
		"amount5":           map[string]interface{}{"value": amountStr},
		"thing3":            map[string]interface{}{"value": item.PlaceName},
	}

	params := map[string]interface{}{
		"touser":      item.Openid,
		"template_id": item.TemplateId,
		"page":        "/pages/cuse/cuse?devicesn=" + item.DeviceSn,
		"data":        data,
	}

	return params
}

// 订单号{{character_string7.DATA}}
// 订单状态{{phrase6.DATA}}
// 商家名称{{thing9.DATA}}
// 下单时间{{time4.DATA}}
// 温馨提示{{thing1.DATA}}
// 订单状态通知
func (task *TaskLogic) WeChatAppOrderStatusTemplate(item *message.OrderAndMessageModel) map[string]interface{} {
	payTime, _ := time.ParseInLocation("2006-01-02 15:04:05", item.CreateTime, time.Local)
	useMinute := int((time.Now().Unix() - payTime.Unix()) / 60)

	data := map[string]interface{}{
		"character_string7": map[string]interface{}{"value": item.TradeNo},
		"phrase6":           map[string]interface{}{"value": "服务中"},
		"thing9":            map[string]interface{}{"value": item.PlaceName},
		"time4":             map[string]interface{}{"value": item.CreateTime},
		"thing1":            map[string]interface{}{"value": fmt.Sprintf("已使用%d分钟，再次扫码可结束使用", useMinute)},
	}

	params := map[string]interface{}{
		"touser":      item.Openid,
		"template_id": item.TemplateId,
		"page":        "/pages/cuse/cuse?devicesn=" + item.DeviceSn,
		"data":        data,
	}

	return params
}

// WeChatAppEvaluateTemplate
// 门店名称 {{thing1.DATA}}
// 备注 {{thing5.DATA}}
// 服务评价提醒
func (task *TaskLogic) WeChatAppEvaluateTemplate(item *message.MessageFixedModel) map[string]interface{} {
	data := map[string]interface{}{
		"thing1": map[string]interface{}{"value": item.PlaceName},
		"thing5": map[string]interface{}{"value": "好评有礼，精品礼物快领取吧"},
	}

	params := map[string]interface{}{
		"touser":      item.Openid,
		"template_id": item.TemplateId,
		"page":        "/pages/evaluateGift/evaluateGift?q=https%3A%2F%2Fdev.kdcgx.com%2Fpcl10032%2Fdev%2F" + item.DeviceSn,
		"data":        data,
	}

	return params
}
